package gobang_util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import exception.DAOException;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;

public class DbUtil {
	private static final ThreadLocal<Connection> connects = new ThreadLocal<>();

	private static String host = null;// 数据库ip
	private static String port = null;// 数据库端口
	private static String SQLAccont = null;// 数据库账户
	private static String SQLPassword = null;// 数据库密码
	private static String SQLName = null;// 数据库密码

	// 用于读取properties
	static {
		Properties properties = new Properties();
		try {
			FileInputStream input = new FileInputStream("config.properties");
			properties.load(input);
			host = properties.getProperty("host");
			port = properties.getProperty("port");
			SQLAccont = properties.getProperty("account");
			SQLPassword = properties.getProperty("password");
			SQLName = properties.getProperty("sqlname");

		} catch (FileNotFoundException e) {
			Alert alert = new Alert(AlertType.ERROR);
			alert.setContentText("未找到数据库配置文件");
			alert.setTitle("错误");
			alert.show();
			e.printStackTrace();
		} catch (IOException e) {
			Alert alert = new Alert(AlertType.ERROR);
			alert.setContentText("系统维护中");
			alert.setTitle("错误");
			alert.show();
			e.printStackTrace();
		}
	}

	private DbUtil() {
	}

	/**
	 * 连接数据库
	 * 
	 * @return 数据库连接对象
	 */
	public static Connection getConnection() {
		// 确保同一个连接
		Connection connect = connects.get();
		if (connect == null) {
			try {
				connect = DriverManager.getConnection(
						"jdbc:mysql://" + host + ":" + port + "/" + SQLName + "?" + "serverTimezone=UTC", SQLAccont,
						SQLPassword);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connects.set(connect);
		}
		return connect;
	}

	// 关闭资源
	public static void closeAll(Connection connect, Statement statement, ResultSet resultset) {
		try {
			if (resultset != null) {
				resultset.close();

			}
			if (statement != null) {
				statement.close();
			}
			if (connect != null) {
				connect.close();
				connects.remove();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param sql
	 * @param param
	 */
	public static void executeSQL(String sql, Object... param) {
		Connection connect = DbUtil.getConnection();
		PreparedStatement pstmt = null;
		try {
			pstmt = connect.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				pstmt.setObject(i + 1, param[i]);
			}
			pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException("SQL操作异常", e);
		} finally {
			closeAll(null, pstmt, null);
		}
	}
}
